import React, { Component, useState } from "react";
import { connect } from "dva";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import Ellipsis from "@/components/Ellipsis";
import { NAME_RULE, CODE_RULE } from "@/Constants/rules";
import { Menu, Dropdown, Icon, message, Form, Modal, Input, Tree } from "antd";
import styles from "./Role.less";
import Content from "./Content";

const FormItem = Form.Item;
const { TreeNode } = Tree;
var lll = "";
var platformid = 5;
var parentUserId = 0;

@connect(({ role, loading, user }) => ({
  // sysRoots: role.sysRoots,
  roleList: role.roleList,
  treeData: role.treeData,
  createLoading: loading.effects["role/createRole"],
  updateLoading: loading.effects["role/updateRole"],
  currentUser: user.currentUser,
  countLength: role.countLength,
}))
@Form.create()
class Role extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentSys: {},
      currentRoleId: 2,
      modalVisible: false,
      roleAction: "",
    };
    this.menuRef = React.createRef();
  }

  componentDidMount() {
    // const { dispatch } = this.props;
    // dispatch({ type: 'role/fetchSysRoots' }).then(res => {
    //   const { sysRoots } = this.props;
    //   if (sysRoots[0]) {
    //     this.fetchRoleList(sysRoots[0].id).then(res => {
    //       const { roleList } = this.props;
    //       const roleId = (roleList[0] || {}).id;
    //       this.setState({
    //         currentRoleId: roleId,
    //       });
    //       roleId && this.queryMembersByRole(roleId);
    //     });
    //     this.setState({
    //       currentSys: sysRoots[0],
    //     });
    //   }
    // });
    this.fetchRoleList();
    this.queryMembersByRole();
  }

  scrollMenu = (y) => {
    this.menuRef.current.children[0].scrollTo(0, y);
  };

  fetchRoleList = () => {
    const { dispatch } = this.props;
    return dispatch({
      type: "role/fetchRoleList",
      payload: {
        data: {
          parentUserId: parentUserId,
          platform: platformid,
        },
      },
    }).then((res) => {
      console.log(res);
    });
  };

  queryMembersByRole = (roleId = 2) => {
    const { dispatch } = this.props;
    return dispatch({
      type: "role/queryMembersByRole",
      payload: {
        // pathParams: {
        //   roleId,
        // },
        data: {
          platform: platformid,
          roleId,
          parentUserId: parentUserId,
          pageIndex: 1,
          pageSize: 50,
        },
      },
    }).then((res) => {
      console.log(res);
      if (roleId == 2) {
        dispatch({
          type: "role/StartcountLength",
          payload: {
            id: res.data.querySysUserDto.totalCount,
          },
        });
      }
    });
  };

  // initRoleUserList = () => {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: "role/saveRoleUserList",
  //     payload: {
  //       list: [],
  //       pagination: {},
  //     },
  //   });
  // };

  fetchRoleTree = (id) => {
    const { dispatch } = this.props;
    return dispatch({
      type: "role/fetchRoleTree",
      payload: {
        // pathParams: {
        //   roleId: id,
        // },
        data: {
          parentUserId: parentUserId,
          platform: platformid,
        },
      },
    });
  };

  initRoleTree = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "role/saveTreeData",
      payload: [],
    });
    dispatch({
      type: "role/saveCheckedTreeNode",
      payload: [],
    });
  };

  handleButtonClick = (e) => {
    message.info("Click on left button.");
    console.log("click left button", e);
  };

  handleModalVisible = () => {
    this.setState({
      modalVisible: false,
    });
  };

  okHandle = () => {
    const { form, dispatch, createLoading, updateLoading } = this.props;
    if (createLoading || updateLoading) return;
    const { currentRoleId, currentSys, roleAction } = this.state;
    form.validateFields(async (err, fieldsValue) => {
      if (err) return;
      let res;
      if (roleAction === "create") {
        console.log(fieldsValue);
        res = await dispatch({
          type: "role/addSureRole",
          payload: {
            // pathParams: {
            //   rootId: currentSys.id,
            // },
            data: {
              // menuIds: this.props.form.getFieldValue('menuIds'),
              menuIds: lll,
              parentUserId: parentUserId,
              platform: platformid,
              roleName: this.props.form.getFieldValue("roleName"),
            },
          },
        });
        await this.fetchRoleList(currentSys.id);
        const { roleList } = this.props;
        this.scrollMenu(9999);
        this.handleMenuClick({
          key: roleList[roleList.length - 1].id,
        });
      } else {
        res = await dispatch({
          type: "role/updateRole",
          payload: {
            // pathParams: {
            //   id: currentRoleId,
            // },
            data: {
              // ...fieldsValue,
              platform: platformid,
              roleId: currentRoleId,
              roleName: this.props.form.getFieldValue("roleName"),
            },
          },
        });
        this.fetchRoleList(currentSys.id);
      }

      if (res.code === 200) {
        message.success(roleAction === "create" ? "添加成功" : "修改成功");
      }
      this.setState({
        modalVisible: false,
      });
    });
  };

  deleteRole = () => {
    const { dispatch } = this.props;
    const { currentRoleId, currentSys } = this.state;
    Modal.confirm({
      title: "删除",
      content: "确定删除所选角色吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {
        const res = await dispatch({
          type: "role/deleteRole",
          payload: {
            // pathParams: {
            //   id: currentRoleId,
            // },
            data: {
              parentUserId: parentUserId,
              platform: platformid,
              roleId: currentRoleId,
            },
          },
        });
        await this.fetchRoleList(currentSys.id);
        const { roleList } = this.props;

        if (res.code === 200) {
          message.success("删除成功");
        }
        if (roleList.length > 0) {
          this.handleMenuClick({ key: roleList[0].id });
          this.scrollMenu(0);
        } else {
          this.setState({ currentRootId: "" });
          dispatch({
            type: "role/saveRoleUserList",
            payload: {
              list: [],
              pagination: {},
            },
          });
        }
      },
    });
  };

  modifyRole = () => {
    const { roleList } = this.props;
    this.setState({
      modalVisible: true,
      roleAction: "modify",
    });
    console.log(roleList);
  };

  // 添加角色分组权限请求
  createRole = () => {
    this.setState({
      modalVisible: true,
      roleAction: "create",
    });
    const { dispatch } = this.props;
    return dispatch({
      type: "role/createRole",
      payload: {
        data: {
          parentUserId: parentUserId,
          platform: platformid,
        },
      },
    }).then((res) => {
      console.log(res);
    });
  };

  // switchSystem = e => {
  //   const { sysRoots } = this.props;
  //   this.setState({
  //     currentSys: sysRoots.find(sys => sys.id === e.key) || {},
  //   });
  //   this.fetchRoleList(e.key).then(res => {
  //     const { roleList } = this.props;
  //     const roleId = (roleList[0] || {}).id;
  //     this.setState({
  //       currentRoleId: roleId,
  //     });
  //     if (roleId) {
  //       this.queryMembersByRole(roleId);
  //       this.fetchRoleTree(roleId);
  //     } else {
  //       this.initRoleUserList();
  //       this.initRoleTree();
  //     }
  //   });
  // };

  handleSubMenuClick = (e) => {
    e.domEvent.stopPropagation();
    e.key === "1" ? this.deleteRole() : this.modifyRole();
  };

  handleMenuClick = (e) => {
    const { dispatch } = this.props;
    console.log(e);
    this.setState({
      currentRoleId: e.key,
    });
    dispatch({
      type: "role/changeRoleId",
      payload: {
        id: e.key,
      },
    });
    console.log(e.key);
    this.queryMembersByRole(e.key);
    this.fetchRoleTree(e.key);
    this.editOrgTree(e.key);
  };

  editOrgTree = (roleId) => {
    if (roleId === undefined || "" || null) {
      return false;
    }
    const { dispatch } = this.props;
    dispatch({
      type: "role/editOrgTree",
      payload: {
        data: {
          roleId,
          parentUserId: parentUserId,
          platform: platformid,
        },
      },
    }).then((res) => {
      console.log(res);
      // console.log(roleId);
      const { data } = res;

      // 转化复选框选中的值
      let arr = [];
      function a(data) {
        data.find((item) => {
          if (item.children.length === 0 && item.checked == true) {
            arr.push(item);
          }
          if (item.children.length > 0 && item.checked == true) {
            a(item.children);
          }
        });
        return arr;
      }
      let newArr = a(data);
      console.log(newArr);
      var hello = newArr.map((item) => item.menuId);
      console.log(hello);

      dispatch({
        type: "role/editOrgTreeList",
        payload: data,
      });
      console.log(data);

      dispatch({
        type: "role/newcheckedList",
        payload: {
          id: hello,
        },
      });
    });
  };

  validateRoleCode = (rule, value, callback) => {
    const { dispatch } = this.props;
    const { currentSys, roleAction } = this.state;
    if (roleAction === "modify") {
      callback();
      return;
    }

    let queryParams = {
      code: value,
      rootId: currentSys.id,
    };
    dispatch({
      type: "role/validateRoleCode",
      payload: {
        queryParams,
      },
    }).then((res) => {
      if (!res.data) {
        callback("编码重复");
      }
      callback();
    });
  };

  renderTreeNode = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.menuId} dataRef={item}>
            {this.renderTreeNode(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.menuId} />;
    });
  };

  render() {
    const { roleList, form, createLoading, updateLoading } = this.props;
    const { modalVisible, currentSys, roleAction, currentRoleId } = this.state;
    const currentRole =
      roleList.find((role) => role.roleId === currentRoleId) || {};
    const actionMenu = (
      <Menu onClick={this.handleSubMenuClick}>
        <Menu.Item key="0">
          <Icon type="edit" />
          &nbsp;编辑
        </Menu.Item>
        <Menu.Item key="1">
          <Icon type="delete" />
          &nbsp;删除
        </Menu.Item>
      </Menu>
    );
    // const sysMenu = (
    //   <Menu onClick={this.switchSystem}>
    //     {(sysRoots || []).map(item => {
    //       return <Menu.Item key={item.id}>{item.name}</Menu.Item>;
    //     })}
    //   </Menu>
    // );

    const roleMenu = (
      <Menu
        className={styles.menu}
        // selectedKeys={[this.state.currentRoleId]}
        defaultSelectedKeys={["2"]}
        onClick={this.handleMenuClick}
        mode="inline"
      >
        {(roleList || []).map((role) => {
          console.log(roleList);
          console.log(role.roleId);
          if (role.roleId == 2) {
            role.userCount = this.props.countLength;
          }
          return role.adminFlag == false ? (
            <Menu.Item key={role.roleId} className={styles.menuItem}>
              <span>
                <Ellipsis tooltip length={10} className={styles.ellipsis}>
                  {role.roleName + "(" + role.userCount + ")"}
                </Ellipsis>
              </span>
              <Dropdown
                className={styles.showEllipsis}
                key={role.roleId}
                overlay={actionMenu}
                trigger={["click"]}
                placement="bottomLeft"
              >
                <Icon type="ellipsis" />
              </Dropdown>
            </Menu.Item>
          ) : (
            <Menu.Item key={role.roleId} className={styles.menuItem}>
              <span>
                <Ellipsis tooltip length={10} className={styles.ellipsis}>
                  {role.roleName + "(" + role.userCount + ")"}
                </Ellipsis>
              </span>
            </Menu.Item>
          );
        })}
      </Menu>
    );

    const Tree1 = () => {
      const [expandedKeys, setExpandedKeys] = useState([]);
      const [checkedKeys, setCheckedKeys] = useState([]);
      const [selectedKeys, setSelectedKeys] = useState([]);
      const [autoExpandParent, setAutoExpandParent] = useState(true);

      const onExpand = (expandedKeys) => {
        console.log("onExpand", expandedKeys);
        setExpandedKeys(expandedKeys);
        setAutoExpandParent(false);
      };

      const onCheck = (checkedKeys, e) => {
        console.log(e);
        let checkedKey = [...checkedKeys, ...e.halfCheckedKeys];
        setCheckedKeys(checkedKeys);
        console.log(checkedKey);
        e.abc = checkedKey.join(",");
        console.log(e.abc);
        lll = e.abc;
        console.log(lll);
      };

      const onSelect = (selectedKeys, info) => {
        console.log("onSelect", info);
        setSelectedKeys(selectedKeys);
      };

      return (
        <Tree
          checkable
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
        >
          {this.renderTreeNode(this.props.treeData)}
        </Tree>
      );
    };

    return (
      <PageHeaderWrapper title="角色管理">
        <div className={styles.main}>
          <div className={styles.leftmenu}>
            <div className={styles.menuTop}>
              {/* <Dropdown trigger={["click"]} placement="bottomLeft"> */}
              <span placement="bottomLeft">
                <div className={styles.select}>角色分组</div>
              </span>
              <div>
                <Icon
                  type="plus-circle"
                  onClick={this.createRole}
                  style={{
                    fontSize: "18px",
                    marginRight: "5px",
                    marginTop: "5px",
                    color: "#bbb",
                  }}
                />
              </div>
            </div>
            <div ref={this.menuRef}>{roleMenu}</div>
          </div>
          <div
            style={{ display: currentRoleId ? "block" : "none" }}
            className={styles.right}
          >
            <Content currentRoleId={currentRoleId} />
          </div>
        </div>
        <Modal
          maskClosable={false}
          keyboard={false}
          destroyOnClose
          title={roleAction === "create" ? "添加角色" : "编辑角色"}
          visible={modalVisible}
          confirmLoading={createLoading || updateLoading}
          onOk={this.okHandle}
          onCancel={this.handleModalVisible}
        >
          {roleAction === "create" ? (
            <>
              <FormItem
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 15 }}
                label="角色名称"
              >
                {form.getFieldDecorator("roleName", {
                  // initialValue: roleAction === 'create' ? currentRole.roleName : '',
                  initialValue: currentRole.roleName,
                  rules: [
                    {
                      required: true,
                      message: "请输入名称",
                      whitespace: true,
                    },
                    {
                      pattern: NAME_RULE.PATTERN,
                      message: NAME_RULE.MESSAGE,
                    },
                  ],
                })(<Input maxLength={30} />)}
              </FormItem>

              <FormItem
                label="角色权限"
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 15 }}
              >
                {form.getFieldDecorator("menuIds", {
                  initialValue: lll,
                  // rules: [
                  //   {
                  //     required: true,
                  //     message: '请选择角色权限',
                  //   },
                  // ],
                })(<Tree1 />)}
              </FormItem>
            </>
          ) : (
            <FormItem
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 15 }}
              label="角色名称"
            >
              {form.getFieldDecorator("roleName", {
                initialValue:
                  roleAction === "modify" ? currentRole.roleName : "",
                rules: [
                  {
                    required: true,
                    message: "请输入名称",
                    whitespace: true,
                  },
                  {
                    pattern: NAME_RULE.PATTERN,
                    message: NAME_RULE.MESSAGE,
                  },
                ],
              })(<Input maxLength={30} />)}
            </FormItem>
          )}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Role;
